<?php
declare(strict_types=1);

namespace app\common\service\sms;

use app\common\trait\ResultTrait;
use app\common\service\sms\driver\SmsInterface;
use app\model\api\admin\general\SmsLog;

/**
 * 短信基础类
 */
abstract class Driver implements SmsInterface
{
    use ResultTrait;
    /**
     * 驱动句柄
     * @var object
     */
    protected $handler = null;

    /**
     * 配置参数
     * @var array
     */
    protected $config = [];

    /**
     * 返回句柄对象，可执行其它高级方法
     *
     * @access public
     * @return object
     */
    public function handler()
    {
        return $this->handler;
    }

    public function __call($method, $args)
    {
        return call_user_func_array([$this->handler, $method], $args);
    }

    /**
     * 日志记录
     * @param string $channel 渠道
     * @param string $phone 手机号
     * @param array $message 短信内容 content:内容, template:模板ID, data:模板变量
     * @param bool|string $success_or_fail 发送状态
     */
    public function log(string $channel, string $phone, array $message = [], bool|string $success_or_fail = true): void
    {
        $message['data'] = desensitization($message['data']);

        $log = new SmsLog();
        $log->save([
            'channel' => $channel,
            // 'type' => 1,
            'phone' => $phone,
            'content' => json_encode($message['content'] ?? [], JSON_UNESCAPED_UNICODE),
            'template' => $message['template'] ?? '',
            'data' => json_encode($message['data'] ?? [], JSON_UNESCAPED_UNICODE),
            'status' => $success_or_fail === true ? SmsLog::STATUS['SUCCESS'][0] : SmsLog::STATUS['FAILURE'][0],
            'fail_msg' => $success_or_fail === true ? '' : $success_or_fail,
        ]);
    }
}
